var request = require('request'),
	cheerio = require('cheerio'),
	baseUrl = 'http://www.nasdaq.com/earnings/earnings-calendar.aspx?date={0}',
	year = parseInt(process.argv[2]),
	month = parseInt(process.argv[3]) - 1,
	date = parseInt(process.argv[4]),
	dateString = formatDate(year, month, date),
	url = baseUrl.replace('{0}', dateString),
	headers = { 
		'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0'
	};
	
request.get({url: url, headers: headers}, function(err, resp, body) {
	var $ = cheerio.load(body),
		$trs = $($('.USMN_EarningsCalendar').get(0)).find('tr'),
		statements = [],
		statementsString;
	
	$trs = $trs.slice(1);
	
	$trs.each(function(i, tr){
		var $tds = $(tr).find('td'),
			statement = {
				Time: getTime($($tds.get(0)).find('a').attr('title')),
				Ticker: getTicker($($tds.get(1)).text()),
				Date: $($tds.get(2)).text().trim()
			};
		
		statements.push(statement);
	});

	statementsString = JSON.stringify(statements);
	console.log(statementsString);
});

function formatDate(year, month, date){
	var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
		dateString = '{0}-{1}-{2}'
			.replace('{0}', year)
			.replace('{1}', months[month])
			.replace('{2}', date);
	
	return dateString;		
}

function getTicker(text){
	return text
		.substring(text.lastIndexOf('(') + 1, text.lastIndexOf(')'))
		.trim();
}

function getTime(text){
	text = text || '';
	
	if (text.toLowerCase().indexOf('pre') >= 0) {
		return 'Before';
	}
	
	if (text.toLowerCase().indexOf('after') >= 0) {
		return 'After';
	}
	
	return 'NA'
}